package jfilters.filters.color;

/*
    Copyright Janne Liljeblad 2008.

    This file is part of JFilters.

    JFilters is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    JFilters is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with JFilters.  If not, see <http://www.gnu.org/licenses/>.
*/

import jfilters.filters.SimpleLookUpFilter;

public class JFBrightnessContrast extends SimpleLookUpFilter
{
	private double brightness;
	private double contrast;

	public JFBrightnessContrast()
	{
		initlookUp();
	}

	//--- range -1 - 1
	public void setBrightness( double brightness )
	{
		this.brightness = brightness;
		initlookUp();
	}
	//--- range -1 - 1
	public void setContrast(double contrast)
	{
		this.contrast = contrast;
		initlookUp();
	}

	protected double lut_func( double value )
	{
		double nvalue;
		double power;
		
		//--- range -1 , 1
		if ( brightness < 0.0 )
			value = value * (1.0 + brightness );
		else
			value = value + ((1.0 - value ) * brightness );
		
		// range -1, 1 
		if ( contrast < 0.0)
		{
			if (value > 0.5)
				nvalue = 1.0 - value;
			else
				nvalue = value;
			
			if (nvalue < 0.0)
				nvalue = 0.0;
			
			nvalue = 0.5 * Math.pow( nvalue * 2.0 , (double) (1.0 + contrast));
			
			if (value > 0.5)
				value = 1.0 - nvalue;
			else
				value = nvalue;
		}
		else
		{
			if (value > 0.5)
				nvalue = 1.0 - value;
			else
				nvalue = value;
			
			if (nvalue < 0.0)
				nvalue = 0.0;
			
			power = (contrast == 1.0) ? 127 : 1.0 / (1.0 - contrast);
			nvalue = 0.5 * Math.pow (2.0 * nvalue, power);
			
			if (value > 0.5)
				value = 1.0 - nvalue;
			else
				value = nvalue;
		}
		
		return value;
	}

}//end class